﻿using SiteNavigation.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace SiteNavigation.Services
{
    public class SiteManageService : ISiteManageService
    {
        private readonly SiteNavigationDbContext _db;

        public SiteManageService(SiteNavigationDbContext siteNavigationDbContext)
        {
            _db = siteNavigationDbContext;
        }

        public async Task<List<SiteEntity>> GetAllAsync()
        {
            return await _db.Sites.AsNoTracking().ToListAsync();
        }

        public async Task<SiteEntity> GetByIdAsync(int id)
        {
            return await _db.Sites.AsNoTracking().Where(a => a.Id.Equals(id)).FirstOrDefaultAsync();
        }

        public async Task RemoveByIdAsync(int id)
        {
            var site = await _db.Sites.AsNoTracking().Where(a => a.Id.Equals(id)).FirstOrDefaultAsync();
            if(site == null)
            {
                throw new OperationFailedException("未找到要删除的站点");
            }

            _db.Sites.Remove(site);
            await _db.SaveChangesAsync();
        }

        public async Task SaveAsync(SiteEntity entity)
        {
            entity.LastUpdatedTime = DateTime.Now;
            if (entity.Id > 0)
            {
                // Update
                var history = await _db.Sites.Where(a => a.Id.Equals(entity.Id)).FirstOrDefaultAsync();
                if(history == null)
                {
                    throw new OperationFailedException("未找到要更新的站点");
                }
                history.Name = entity.Name;
                history.IndexUrl = entity.IndexUrl;
                history.AdminUrl = entity.AdminUrl;
                await _db.SaveChangesAsync();
            }
            else
            {
                // Create
                await _db.Sites.AddAsync(entity);
                await _db.SaveChangesAsync();
            }
        }
    }
}
